"""

关于发送请求的所有内容
"""
import re
import json
from urllib.parse import urlparse
from jsonpath_rw import parse
import requests

from conf import settings




# ----------------------------- 以下： 实现cookie的第二种方式 -----------------------------

class RequestOperator(object):

	def __init__(self, case_name, case_content, case_dict):
		self.case_name = case_name
		self.case_content = case_content
		self.case_dict = case_dict   # 存放所有用例信息的字典

	@property
	def get_msg(self):
		""" 获取请求结果 """
		url = settings.CURRENT_SERVER + self.case_content['url']
		request_headers = self._check_request_params('headers')
		response = requests.request(
			method=self.case_content['method'],
			url=url,
			params=self._check_request_params('params'),
			headers=request_headers,
			data=self._check_request_params('data'),
			json=self._check_request_params('json'),
			cookies=self._check_cookie(),
			timeout=2,
		)
		self._write_data(response)
		return response, request_headers

	def _write_data(self, response):
		""" 将请求结果中有用的信息都写到当前用例的字典中 """
		# 写cookie
		cookie = response.cookies.get_dict()
		self.case_dict[self.case_name]['tmp_response_cookie'] = cookie
		# 写响应头，响应体
		self.case_dict[self.case_name]['tmp_response_headers'] = response.headers
		self.case_dict[self.case_name]['tmp_response_json'] = response.json()
		# 写请求头，请求体
		self.case_dict[self.case_name]['tmp_request_headers'] = self._check_request_params('headers')
		self.case_dict[self.case_name]['tmp_request_data'] = self._check_request_params('data')
		self.case_dict[self.case_name]['tmp_request_json'] = self._check_request_params('json')
		self.case_dict[self.case_name]['tmp_request_params'] = self._check_request_params('params')

	def _check_cookie(self):
		""" 为请求添加上cookie """
		cookie = self.case_content.get("cookies", {})  # 如果有值，说明需要携带cookie
		if cookie:
			# 去依赖的用例中找存储的cookie值
			return self.case_dict[self.case_content['cookies']]['tmp_response_cookie']
		else:
			return {}

	def _check_request_params(self, key):
		""" 检查请求的参数 """
		if self.case_content.get(key, None):
			return self._check_re(self.case_content.get(key, None))
		else:
			return {}

	def _check_re(self, content):
		""" 处理数据依赖 """
		# {"testfan-token": "${neeo_001>response_json>data}$", "userName": "${neeo_001>request_headers>userName}$"}
		# print(222222222222222, content, type(content))
		if isinstance(content, dict):

			content = json.dumps(content)
		# print(11111111111, content)
		pattern = re.compile(r'\${(.*?)}\$')
		match_list = pattern.findall(content)  # ['neeo_001>response_json>data', 'neeo_001>request_headers>userName']
		if match_list:
			# print(11111111, match_list)
			for item in match_list:
				# print(111111, item)  # neeo_001>response_json>data
				tmp_case_name, tmp_params, rule_data = item.split('>')
				# print(tmp_case_name, tmp_params, rule_data)  # neeo_001 response_json data
				data = self.case_dict[tmp_case_name]['tmp_{}'.format(tmp_params)]
				# print(data, type(data))  # {'userName': 'admin', 'password': '1234'} <class 'dict'>
				tmp_match = parse(rule_data).find(data)
				if tmp_match:
					match_result = [i.value for i in tmp_match][0]
					# 将匹配的结果替换到原content中
					content = re.sub(pattern=pattern, repl=match_result, string=content, count=1)
		return json.loads(content)


# ----------------------------- 以下： 实现cookie的第一种方式 -----------------------------
# class RequestOperator(object):
#
# 	def __init__(self, case_name, case_content):
# 		self.case_name = case_name
# 		self.case_content = case_content
#
# 	@property
# 	def get_msg(self):
# 		""" 获取请求结果 """
# 		url = settings.CURRENT_SERVER + self.case_content['url']
# 		response = requests.request(
# 			method=self.case_content['method'],
# 			url=url,
# 			params=self._check_request_params('params'),
# 			headers=self._check_request_params('headers'),
# 			data=self._check_request_params('data'),
# 			json=self._check_request_params('json'),
# 			cookies=self._check_cookie(url),
# 			timeout=2,
# 		)
# 		self._write_cookie(response)
#
# 		return response.json()
#
# 	def _write_cookie(self, response):
# 		""" 请求结果如果有cookie，就写入到cookie管理器中 """
# 		cookie = response.cookies.get_dict()
# 		if cookie:
# 			settings.REQUEST_COOKIES[urlparse(response.url).netloc] = cookie
# 		else:
# 			settings.REQUEST_COOKIES[urlparse(response.url).netloc] = cookie
#
# 	def _check_cookie(self, url):
# 		""" 为请求添加上cookie """
# 		return settings.REQUEST_COOKIES.get(urlparse(url).netloc, {})
#
# 	def _check_request_params(self, key):
# 		""" 检查请求的参数 """
# 		if self.case_content.get(key, None):
# 			return json.loads(self.case_content.get(key, None))
# 		else:
# 			return {}
